package com.ruoyi.cloudpc.service.impl;

import com.ruoyi.cloudpc.domain.CloudOrder;
import com.ruoyi.cloudpc.domain.CloudPromoterApprove;
import com.ruoyi.cloudpc.domain.CloudPromotion;
import com.ruoyi.cloudpc.domain.CloudWithdrawal;
import com.ruoyi.cloudpc.mapper.CloudPromotionMapper;
import com.ruoyi.cloudpc.mapper.CloudWithdrawalMapper;
import com.ruoyi.cloudpc.service.CloudPromotionService;
import com.ruoyi.cloudpc.service.ICloudOrderService;
import com.ruoyi.cloudpc.service.ICloudPromoterApproveService;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author Ten
 */
@Service
public class CloudPromotionServiceImpl implements CloudPromotionService {

    @Autowired
    private ICloudOrderService cloudOrderService;

    @Autowired
    private ISysConfigService configService;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private CloudPromotionMapper cloudPromotionMapper;

    @Autowired
    private CloudWithdrawalMapper cloudWithdrawalMapper;
    @Autowired
    private ICloudPromoterApproveService cloudPromoterApproveService;

    @Override
    public Map<String, Object> hasAuth() {
        String username = SecurityUtils.getUsername();
        CloudOrder cloudOrder = new CloudOrder();
        cloudOrder.setCreateBy(username);
        List<CloudOrder> cloudOrders = cloudOrderService.selectCloudOrderList(cloudOrder);
        // 生效订单
        List<CloudOrder> sxOrders = cloudOrders.stream().filter(item -> item.getStatus() >= 2).collect(Collectors.toList());
        BigDecimal total = new BigDecimal(BigInteger.ZERO);
        for (CloudOrder sxOrder : sxOrders) {
            total = total.add(sxOrder.getTotalAmount());
        }

        Map<String, Object> resultMap = new HashMap<>(3);
        // 累计消费
        resultMap.put("total", total);

        // 系统中的推广阈值
        String promotionThreshold = configService.selectConfigByKey("PromotionThreshold");
        BigDecimal pt = new BigDecimal(promotionThreshold);
//        if (total.compareTo(pt) >= 0) {
//            return true;
//        }
//        return false;

        // 是否可推广
//        resultMap.put("promotion", total.compareTo(pt) >= 0);
        String isPromotion = SecurityUtils.getLoginUser().getUser().getIsPromotion();
        resultMap.put("promotion", "1".equals(isPromotion) ? true : false);

        // 剩余达标额
        resultMap.put("difference", total.subtract(pt));

        // 是否已经是受邀用户
        SysUser currentUser = userService.selectUserByUserName(SecurityUtils.getUsername());
        resultMap.put("hasPromoted", StringUtils.isNotBlank(currentUser.getPromoter()));

        // 是否在申请中及申请的状态
        CloudPromoterApprove cloudPromoterApprove = cloudPromoterApproveService.selectCloudPromoterApproveByUserId(SecurityUtils.getUserId());
        resultMap.put("hasApproving", cloudPromoterApprove != null);// 是否有申请:true有申请，false没有申请
        if (cloudPromoterApprove != null) {
            if (StringUtils.isNotBlank(cloudPromoterApprove.getApproveFlag())) {
                resultMap.put("approveFlag", cloudPromoterApprove.getApproveFlag());// 申请的状态：true已审批，false待审批
                boolean approveFlag = "Y".equals(cloudPromoterApprove.getApproveFlag());
                // approveStatus 审批的状态：true已审批通过，false未审批或审批未通过
                resultMap.put("approveStatus", approveFlag);
                if (!approveFlag) {
                    resultMap.put("approveRemark", cloudPromoterApprove.getRemark());// 申请的状态：true已审批，false待审批
                }
            } else {
                resultMap.put("approveFlag", "");// 申请的状态：true已审批，false待审批
                resultMap.put("approveStatus", false);
            }
        }

        return resultMap;
    }

    @Override
    public int savePromoter(String promoter) {
        String username = SecurityUtils.getUsername();
        if (promoter.equals(username)) {
            throw new RuntimeException("不能将自己作为推广人");
        }
        SysUser currentUser = userService.selectUserByUserName(username);
        if (StringUtils.isNotBlank(currentUser.getPromoter())) {
            throw new RuntimeException("当前用户已存在推广人信息，请勿重复操作");
        }
        currentUser.setPromoter(promoter);
        return userService.updateUser(currentUser);
    }

    /**
     * 查询推广
     *
     * @param fromUserName 推广主键
     * @return 推广
     */
    @Override
    public CloudPromotion selectCloudPromotionByFromUserName(String fromUserName) {
        return cloudPromotionMapper.selectCloudPromotionByFromUserName(fromUserName);
    }

    /**
     * 查询推广列表
     *
     * @param cloudPromotion 推广
     * @return 推广
     */
    @Override
    public List<CloudPromotion> selectCloudPromotionList(CloudPromotion cloudPromotion) {
        // 非admin用户，只能查看自己发展的用户数据
        if (!SecurityUtils.getLoginUser().getUser().isAdmin() && (cloudPromotion.getSearchAll() == null || !cloudPromotion.getSearchAll())) {
            cloudPromotion.setFromUserName(SecurityUtils.getUsername());
        }
        return cloudPromotionMapper.selectCloudPromotionList(cloudPromotion);
    }

    /**
     * 新增推广
     *
     * @param cloudPromotion 推广
     * @return 结果
     */
    @Override
    public int insertCloudPromotion(CloudPromotion cloudPromotion) {
        cloudPromotion.setCreateTime(DateUtils.getNowDate());
        return cloudPromotionMapper.insertCloudPromotion(cloudPromotion);
    }

    /**
     * 修改推广
     *
     * @param cloudPromotion 推广
     * @return 结果
     */
    @Override
    public int updateCloudPromotion(CloudPromotion cloudPromotion) {
        cloudPromotion.setUpdateTime(DateUtils.getNowDate());
        return cloudPromotionMapper.updateCloudPromotion(cloudPromotion);
    }

    /**
     * 推广详情
     * 当前佣金
     * 推广人数
     * 累计收益
     *
     * @return
     */
    @Override
    public Map<String, Object> detail() {
        Map<String, Object> resultMap = new HashMap<>(3);

        CloudPromotion cloudPromotion = new CloudPromotion();
        cloudPromotion.setFromUserName(SecurityUtils.getUsername());
        List<CloudPromotion> cloudPromotions = cloudPromotionMapper.selectCloudPromotionList(cloudPromotion);
//        累计收益
        BigDecimal total = new BigDecimal(0);
        for (CloudPromotion promotion : cloudPromotions) {
            total = total.add(promotion.getCommissionAmount());
        }
        resultMap.put("total", total);
//        当前佣金  查提现记录
        CloudWithdrawal cloudWithdrawal = new CloudWithdrawal();
        cloudWithdrawal.setCreateBy(SecurityUtils.getUsername());
        List<CloudWithdrawal> cloudWithdrawals = cloudWithdrawalMapper.selectCloudWithdrawalList(cloudWithdrawal);
        BigDecimal txMoney = cloudWithdrawals.stream().map(CloudWithdrawal::getMoney).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal current = total.subtract(txMoney);
        resultMap.put("current", current);

//        推广人数
        long promotionCnt = cloudPromotions.stream().map(CloudPromotion::getToUserName).distinct().count();
        resultMap.put("promotionCnt", promotionCnt);

        return resultMap;
    }

//    /**
//     * 批量删除推广
//     *
//     * @param fromUserNames 需要删除的推广主键
//     * @return 结果
//     */
//    @Override
//    public int deleteCloudPromotionByFromUserNames(String[] fromUserNames)
//    {
//        return cloudPromotionMapper.deleteCloudPromotionByFromUserNames(fromUserNames);
//    }
//
//    /**
//     * 删除推广信息
//     *
//     * @param fromUserName 推广主键
//     * @return 结果
//     */
//    @Override
//    public int deleteCloudPromotionByFromUserName(String fromUserName)
//    {
//        return cloudPromotionMapper.deleteCloudPromotionByFromUserName(fromUserName);
//    }
}
